<?php
header("Content-Type:text/html;charset=UTF-8");
/**
 * 测试文件上传
 */
require_once '../settings.php';
set_time_limit(0);

//echo $_SERVER['DOCUMENT_ROOT'];


   $uploaddir = $_SERVER['DOCUMENT_ROOT']."/workspace/pub/";//设置文件保存目录 注意包含/   
//$uploaddir = "./";
$type=array("jpg","gif","bmp","jpeg","png");//设置允许上传文件的类型
   $patch="http://localhost/workspace/aka/news/test/";//程序所在路径
   
//获取文件后缀名函数
function fileext($filename){
	return substr(strrchr($filename, '.'), 1);
}
//生成随机文件名函数   
function random($length){
	$hash = 'kkyoo-ld-';
	$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
	$max = strlen($chars) - 1;
	mt_srand((double)microtime() * 1000000);
	for($i = 0; $i < $length; $i++){
		$hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}


$a=strtolower(fileext($_FILES['file']['name']));
//判断文件类型
if(!in_array(strtolower(fileext($_FILES['file']['name'])),$type)) {
	$text=implode(",",$type);
    echo "您只能上传以下类型文件: ",$text,"<br>";
}
   //生成目标文件的文件名   
   else{
   $filename=explode(".",$_FILES['file']['name']);
   do{
     $filename[0]=random(10); //设置随机数长度
     $name=implode(".",$filename);
     //$name1=$name.".Mcncc";
     $uploadfile=$uploaddir.$name;
   echo $uploadfile.'<br />'.$_FILES['file']['tmp_name'].'<br />';
   }while(file_exists($uploadfile));

   try {
   	
	if ( move_uploaded_file($_FILES['file']['tmp_name'],$uploadfile) ){
		
		$pubfile = str_replace($_SERVER['DOCUMENT_ROOT'], "http://localhost", $uploadfile);
		if (!get_magic_quotes_gpc())
			$tmpfile = str_replace('\\\\', '\\', $_FILES['file']['tmp_name']);
		else $tmpfile = $_FILES['file']['tmp_name'];
		
		 echo "<center>您的文件已经上传完毕 上传图片预览: </center><br><center><img src='{$pubfile}'></center>";
                echo"<br><center><a href='javascrīpt:history.go(-1)'>继续上传</a></center>";
         if( is_uploaded_file($tmpfile) ) {
         	   //输出图片预览
                echo "<center>您的文件已经上传完毕 上传图片预览: </center><br><center><img src='{$pubfile}'></center>";
                echo"<br><center><a href='javascript:history.go(-1)'>继续上传</a></center>";
         }else{
                echo "上传失败！";
              }
       }
   }catch (Exception $e){
   	echo $e->getMessage();
   }
   
}


?>


  <form method="post" action="test004.php" enctype="multipart/form-data">
     <table border=0 cellspacing=0 cellpadding=0 align=center width="100%">
      <tr>
        <td width=55 height=20 align="center"><input type="hidden" name="MAX_FILE_SIZE" value="2000000">文件： </TD>
        <td height="16">
        <input name="file" type="file" value="浏览" >
         
        <input type="submit" value="上传" name="B1">
        </td>
      </tr>
     </table>
</form>

